package sunwin.yoms.service.resource;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import sunwin.yoms.comm.LogConst;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;

/**
 * Created by watson on 2015/12/30.
 */
public class JmsReceive {
    private static boolean threadIsRun = true;
    private static Thread thread;
    private static JmsReceive jmsReceive;

    @Autowired
    private JmsTemplate jmsTemplate = null;

    /**
     * Spring 容器会加载两次构造函数,暂时使用静态字段解决线程多开问题
     */
    public void init(){
        if (thread == null) {
            jmsReceive = this;
            thread = new Runworker(jmsTemplate);
            thread.start();
        }
    }

    /**
     * 释放资源,暂时不知道java程序在哪拦截退出
     * @throws InterruptedException
     */
    public static void release() throws InterruptedException {
        jmsReceive.threadIsRun = false;
        jmsReceive.thread.join();
    }

    public class Runworker extends Thread {
        public Runworker(JmsTemplate jmsTemplate) {
            this.jmsTemplate = jmsTemplate;
        }

        private JmsTemplate jmsTemplate;

        @Override
        public synchronized void run() {
            while (threadIsRun) {

                Message message = null;
                try {
                    message = jmsTemplate.receive("CancelOrder");
                } catch (Exception e){
                    Logger.getLogger(LogConst.RECEIVE_MESSAGE_WIDGET).debug("获取消息发生异常", e);
                }

                if (message instanceof ObjectMessage) {
                    ObjectMessage receiveMassage = (ObjectMessage) message;
                    String msg = null;
                    try {
                        msg = (String) receiveMassage.getObject();
                    } catch (JMSException e) {
                        e.printStackTrace();
                    }
                    if(msg != null){
                        System.out.println(msg);
                        //发送短信
                        Logger.getLogger(LogConst.RECEIVE_MESSAGE_WIDGET).debug("向手机/邮箱发送消息->" + msg);
                    }
                    try {
//                        Properties properties = System.getProperties();
//                        String receiveInterval = properties.getProperty("10");
                        Thread.sleep(Integer.parseInt("10"));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
